<template>
    <view class="server-place">
        <u-toast ref="uToast" /><u-no-network></u-no-network>
        <u-navbar title="我的位置" safeAreaInsetTop fixed placeholder>
            <view class="coreshop-navbar-left-slot" slot="left">
                <u-icon name="arrow-left" size="19" @click="goNavigateBack"></u-icon>
                <u-line direction="column" :hairline="false" length="16" margin="0 8px"></u-line>
                <u-icon name="home" size="22" @click="goHome"></u-icon>
            </view>
            <view slot="right">
            </view>
        </u-navbar>

        <view class="searchBox">
                <u-form-item  :borderBottom="false">
                    <coreshop-select v-model="show" mode="mutil-column-auto" :list="pickerList" :default-value="pickerIndex" @confirm="onConfirm"></coreshop-select>
                    <!-- 注意：由于兼容性差异，如果需要使用前后插槽，nvue下需使用u--input，非nvue下需使用u-input -->
                    <!-- #ifndef APP-NVUE -->
                    <u-input :value="pickerValue" type="select" disabled placeholder="请选择省市区区域">
                        <template slot="suffix">
                            <u-button text="选择" type="success" size="mini" @click="show = true"></u-button>
                        </template>
                    </u-input>
                    <!-- #endif -->
                    <!-- #ifdef APP-NVUE -->
                    <u--input :value="pickerValue" type="select" disabled placeholder="请选择省市区区域">
                        <template slot="suffix">
                            <u-button text="选择" type="success" size="mini" @click="show = true"></u-button>
                        </template>
                    </u--input>
                    <!-- #endif -->
                </u-form-item>

               
                <u-form-item :borderBottom="false">
                    <!-- 注意：由于兼容性差异，如果需要使用前后插槽，nvue下需使用u--input，非nvue下需使用u-input -->
                    <!-- #ifndef APP-NVUE -->
                    <view class="coreshop-bg-white">
                        <u-input v-model="keywords" type="text" placeholder="输入街道信息">
                            <template slot="suffix">
                                <u-button text="查询" type="primary" size="mini" @click="searchKeyWord"></u-button>
                            </template>
                        </u-input>
                        <!-- #endif -->
                        <!-- #ifdef APP-NVUE -->
                        <u--input v-model="keywords" type="text" placeholder="输入街道信息">
                            <template slot="suffix">
                                <u-button text="查询" type="primary" size="mini" @click="searchKeyWord"></u-button>
                            </template>
                        </u--input>
                        <!-- #endif -->
                    </view>
                </u-form-item>

        </view>

        <map id='map'
                ref='map'
                v-bind:style="{height: mapH + 'px'}"
                style="width: 100%;"
                :latitude="latitude"
                :longitude="longitude"
                :controls='controls'
                :markers="covers"
                @regionchange='mapChange'>
        </map>
        <!-- #ifndef APP-PLUS -->
        <cover-image v-bind:style="{left: controlsLeft + 'px', top: controlsTop + 'px'}" class="controls-location" :src="positionIcon"></cover-image>
        <!-- #endif -->
        <view class="map-tools">
            <view class="my-location" @tap="toMyLocation">
                <image class="left" :src="myPositionIcon" mode=""></image>
                <view class="right">
                    <text class="title">我的位置</text>
                    <text class="text">{{myAddress}}</text>
                </view>
            </view>
            <view class="start-place">
                <view class="place">
                    <text class="title">{{tipText}}：</text>
                    <text class="text">{{addressObj.address}}</text>
                </view>
                <view class="tip">{{descText}}</view>
                <button @tap="submitAdress" class="sure" type="primary">确认选择</button>
            </view>
        </view>
    </view>
</template>

<script>
    var QQMapWX = require('./qqmap-wx-jssdk.min.js')
    var qqmapsdk;

    export default {
        data() {
            return {
                mapH: 0,// 地图高度，可在initMapH()中设置高度
                mapW: 0, 			 // 屏幕宽度
                longitude: 0,        // 初始经度
                latitude: 0,         // 初始纬度
                myAddress: '',   	 // 初始地址信息
                addressObj: {        // 地图选点信息
                    longitude: '',
                    latitude: '',
                    address: ''
                },
                rules: {},
                // cover-image的默认 超出屏幕外 不然会有闪烁出现
                controlsLeft: 1000,
                controlsTop: 1000,
                controls: [],  // 地图中心点图标, 可更换iconPath, 详情见官方文档关于map组件的介绍

                tipText: '选择位置',
                descText: '使用当前定位或在地图上标记位置',
                positionIcon: 'https://files.cdn.coreshop.cn/static/images/map/positionIcon.png',
                myPositionIcon: 'https://files.cdn.coreshop.cn/static/images/map/myPositionIcon.png',

                covers: [{
                    'longitude': 0,
                    'latitude': 0
                }],
                qqMapKey: '',
                keywords: '',
                pickerValue: '',
                show: false,
                pickerList: this.$db.get("areaList"),
                province: this.$db.get("areaList"),
                pickerIndex: [0, 0, 0], // picker索引值
                provinceKey: -1,//省份id
                cityKey: -1,//市id
                areaKey: -1,//区域id
                areaId: 0,
                show: false,
            };
        },
        onLoad(e) {
            console.log(e);
            this.pickerValue = e.pickerValue;
            this.areaId = e.areaId;

            this.init();

            this.qqMapKey = this.$store.state.config.qqMapKey;
            qqmapsdk = new QQMapWX({
                key: this.qqMapKey
            })
            var longitude = e.longitude;
            var latitude = e.latitude;
            if (longitude && latitude) {
                this.getOldLocation(longitude, latitude);
            } else {
                this.searchAddressName(this.pickerValue);
            }
            //this.getLocation()

            this.initMapH()
            this.initPositionIcon();
        },
        methods: {
            onConfirm(e) {
                let provinceName = e[0].label;
                let cityName = e[1].label;
                let countyName = e[2].label;
                this.pickerValue = e[0].label + " " + e[1].label + " " + e[2].label
                let data = {
                    provinceName: provinceName,
                    cityName: cityName,
                    countyName: countyName
                }
                this.$u.api.getAreaId(data).then(res => {
                    if (res.status) {
                        this.areaId = res.data;
                        this.init();
                        this.searchAddressName(this.pickerValue);

                    } else {
                        uni.showModal({
                            title: '提示',
                            content: '地区选择出现问题，请重新选择地区',
                            showCancel: false
                        });
                    }
                });
            },
            init() {
                this.getFullPath(this.areaId, this.province);
                this.pickerIndex = [this.provinceKey, this.cityKey, this.areaKey];
            },
            //倒查城市信息
            getFullPath(id, data) {
                for (var i = 0; i < data.length; i++) {
                    if (id == data[i].value) {
                        if (!data[i].children) {
                            this.areaKey = i;
                            return true;
                        } else if (data[i].hasOwnProperty("children")) {
                            if (data[i].children[0] && !data[i].children[0].children) {
                                this.cityKey = i;
                                return true;
                            } else {
                                this.provinceKey = i;
                                return true;
                            }
                        }
                    } else {
                        if (data[i].hasOwnProperty("children")) {
                            if (data[i].children[0] !== undefined) {
                                if (data[i].children[0].hasOwnProperty("children")) {
                                    this.provinceKey = i;
                                } else {
                                    this.cityKey = i;
                                }
                            }
                            if (typeof data[i].children != 'undefined') {
                                var res = this.getFullPath(id, data[i].children);
                                if (res) {
                                    return true;
                                }
                            }
                        }
                    }
                }
            },

            // 初始化地图中心位置的定位图片
            initPositionIcon() {
                setTimeout(() => {
                    // H5 微信小程序 使用<cover-image>
                    // #ifndef APP-PLUS
                    this.controlsLeft = this.mapW / 2 - 10
                    this.controlsTop = this.mapH / 2
                    // #endif

                    // App使用map的controls
                    // #ifdef APP-PLUS
                    var controls = {
                        id: '1',
                        iconPath: this.positionIcon,
                        position: {
                            left: this.mapW / 2 - 10,
                            top: this.mapH / 2 - 100,
                            width: 30,
                            height: 30,
                        },
                        clickable: false
                    }
                    this.controls.push(controls)
                    //console.log(this.controls, '==========');
                    // #endif
                }, 100)
            },
            // 查询现在的位置
            getLocation() {
                let _this = this;
                // #ifdef MP-WEIXIN
                wx.getFuzzyLocation({
                    type: 'wgs84',
                    success(res) {
                        _this.initMap(res)
                    },
                    fail: function () {
                        _this.$u.toast("获取您的经纬度坐标失败")
                    }
                })
                // #endif
                // #ifndef MP-WEIXIN
                uni.getLocation({
                    type: 'wgs84',
                    success: function (res) {
                        _this.initMap(res)
                    },
                    fail: function () {
                        _this.$u.toast("获取您的经纬度坐标失败")
                    }
                });
                // #endif
            },
            // 查询现在的位置
            getOldLocation(longitude, latitude) {
                var res = {
                    longitude: longitude,
                    latitude: latitude
                }
                this.initMap(res)
            },
            // 初始化我的位置
            async initMap(res) {
                this.longitude = res.longitude;
                this.latitude = res.latitude;
                this.myAddress = await this.getAddressName(res);

                this.addressObj = Object.assign({}, this.addressObj, {
                    longitude: res.longitude,
                    latitude: res.latitude,
                    address: this.myAddress
                })
            },
            // 地图选择位置后 查询地点名称
            async checkMap(res) {
                this.addressObj = Object.assign({}, this.addressObj, {
                    longitude: res.longitude,
                    latitude: res.latitude,
                    address: await this.getAddressName(res)
                })
                //console.log('当前位置:' + res.latitude + '|' + res.longitude);
            },

            // 监听地图位置变化
            mapChange(e) {
                let that = this
                clearTimeout(this.timer)
                this.timer = setTimeout(() => {
                    if (e.type == 'regionchange' || e.type == 'end') {
                        that.mapCtx = uni.createMapContext('map', this)
                        that.mapCtx.getCenterLocation({
                            success: res => {
                                this.checkMap(res)
                            },
                            fail: err => {
                                console.log(err);
                            }
                        })
                    }
                }, 200)
            },
            // 查询地图中心点的名称
            getAddressName(addressObj) {
                return new Promise((res) => {
                    // #ifdef APP-PLUS
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: addressObj.latitude,
                            longitude: addressObj.longitude
                        },
                        get_poi: 1,
                        poi_options: "page_size=1;page_index=1",
                        output: 'jsonp',
                        success: (e) => {
                            res(e.result.formatted_addresses.recommend);
                        },
                        fail: err => {
                            res(err);
                        }
                    })
                    // #endif

                    // #ifdef MP-WEIXIN
                    qqmapsdk.reverseGeocoder({
                        location: {
                            latitude: addressObj.latitude,
                            longitude: addressObj.longitude
                        },
                        get_poi: 1,
                        poi_options: "page_size=1;page_index=1",
                        output: 'jsonp',
                        success: (e) => {
                            res(e.result.formatted_addresses.recommend);
                        },
                        fail: err => {
                            res(err);
                        }
                    })
                    // #endif
                })

            },
            searchKeyWord() {
                var _this = this;
                if (_this.keywords) {
                    var keyword = _this.pickerValue + ' ' + _this.keywords;
                    this.searchAddressName(keyword);
                } else {
                    this.$u.toast("请输入需要查询的地名");
                }
            },
            searchAddressName(keyword) {
                this.keywords = '';
                var _this = this;
                // #ifdef APP-PLUS
                // #endif

                // #ifdef H5
                // #endif

                // #ifdef MP-WEIXIN
                qqmapsdk.geocoder({
                    address: keyword,
                    output: 'jsonp',
                    success: (e) => {
                        console.log(e);
                        if (e.status == 0) {
                            let res = {
                                longitude: e.result.location.lng,
                                latitude: e.result.location.lat,
                            }
                            _this.initMap(res);
                        } else {
                            _this.$u.toast(e.message);
                        }
                    },
                    fail: err => {
                        if (err.status != 0) {
                            _this.$u.toast(err.message);
                        }
                        console.log(err);
                    }
                })
                // #endif
            },
            // 计算地图的高度
            initMapH() {
                // #ifdef APP-PLUS
                this.mapW = uni.getSystemInfoSync().windowWidth
                this.mapH = uni.getSystemInfoSync().windowHeight;
                // #endif
                // #ifndef APP-PLUS
                this.mapW = uni.getSystemInfoSync().windowWidth
                this.mapH = uni.getSystemInfoSync().windowHeight;
                // #endif
            },
            // 移动到我的位置
            toMyLocation() {
                this.getLocation()
            },
            // 提交
            submitAdress() {
                this.controls = []

                let pages = getCurrentPages();//当前页
                let beforePage = pages[pages.length - 2];//上个页面

                // #ifdef MP-ALIPAY || MP-TOUTIAO
                this.$db.set('addressObj', this.addressObj, true);
                // #endif

                // #ifdef APP-PLUS || APP-PLUS-NVUE
                this.$store.commit("addressObj", this.addressObj)
                // #endif

                // #ifdef MP-WEIXIN
                beforePage.$vm.form.longitude = this.addressObj.longitude;
                beforePage.$vm.form.latitude = this.addressObj.latitude;
                beforePage.$vm.form.street = this.addressObj.address;
                beforePage.$vm.form.pickerValue = this.pickerValue;
                beforePage.$vm.form.areaId = this.areaId;
                // #endif
                uni.navigateBack({
                    delta: 1
                });
            }
        }
    };
</script>

<style scoped lang="scss">
    @import "map.scss";
</style>
